import java.io.*;
import java.util.Scanner;

public class Demo13 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的文件目录路径：");
        String searchPath = sc.next();
        System.out.println("请输入要查询的关键字：");
        String searchWord = sc.next();

        File searchFile = new File(searchPath);
        if(!searchFile.isDirectory()){
            System.out.println("输入的文件目录非法！");
            return;
        }
        search(searchFile,searchWord);
    }

    private static void search(File searchFile, String searchWord) {
        File[] files = searchFile.listFiles();
        if(files == null) return;
        for(File f : files){
            if(f.isFile()){
                //查找关键字
                FindWord(f,searchWord);
            }else{
                search(f,searchWord);
            }
        }
    }

    private static void FindWord(File f, String searchWord) {
        try(Reader reader = new FileReader(f)){
            StringBuilder stringBuilder = new StringBuilder();
            while(true){
                int n = reader.read();
                if(n == -1) break;
                stringBuilder.append((char) n);
            }
            if(stringBuilder.indexOf(searchWord) >= 0){
                System.out.println("找到匹配结果：" + f.getCanonicalFile());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
